import React, {useEffect, useState, useRef} from "react";
import {Input, Button, List, Space} from 'antd';
import ReconnectingWebSocket from 'reconnecting-websocket';

export default function Chat() {
    interface DataType {
        role?: string;
        content?: string;
    }

    const {TextArea} = Input;
    const [message, setMessage] = useState("");
    const [data, setData] = useState<DataType[]>([]);
    const [list, setList] = useState<DataType[]>([]); // 用来页面显示

    const webSocket = useRef<ReconnectingWebSocket>();
    useEffect(() => {
        if (!webSocket.current) {
            webSocket.current = new ReconnectingWebSocket("ws://localhost:9901/xfspark");
            webSocket.current.onopen = () => {
                console.log('websocket 连接成功');
            };
            webSocket.current.onmessage = (event) => {
                const newData = data.concat(JSON.parse(event.data));
                setList(newData);
                data.push(JSON.parse(event.data));
            };
            webSocket.current.onclose = () => {
                console.log('websocket 连接关闭');
            };
            webSocket.current.onerror = () => {
                console.log('websocket 连接错误');
            }
        }

    }, []);

    const sendMessage = (content: string) => {
        webSocket.current?.send(content);
    }

    const doSearch = () => {
        const content = message.trim();
        const messageData: DataType = {role: "user", content: content};
        const newData = data.concat(messageData);
        setList(newData);
        data.push(messageData);
        setMessage("");
        sendMessage(JSON.stringify(messageData));
    };

    return (
        <>
            <div style={{width: '90%', margin: '0 auto', alignItems : 'center', justifyContent : 'center'}}>
                <Space direction="vertical" size={[8, 16]} style={{ display: 'flex' }}>
                    <List
                        size="large"
                        itemLayout="vertical"
                        dataSource={list}
                        renderItem={(item) => (
                            <List.Item>
                                <List.Item.Meta title={item.role} description={item.content}/>
                            </List.Item>
                        )}
                    />
                    <TextArea rows={4} value={message} onChange={e => setMessage(e.target.value)}/>
                    <Button type="primary" onClick={doSearch}> 提 问 </Button>
                </Space>
            </div>

        </>
    );
}